from django.utils import timezone
from analysis.models import StudyRecommendation, KnowledgeMasteryProfile
from analysis.services import AnalysisService


class RecommendationService:
    """学习推荐服务"""

    def generate_recommendations(self, student, max_recommendations=5):
        """生成学习推荐"""
        # 获取薄弱知识点
        weak_profiles = KnowledgeMasteryProfile.objects.filter(
            student=student,
            mastery_level__lt=0.7  # 掌握度低于70%的认为是薄弱点
        ).select_related('knowledge_point').order_by('mastery_level')[:10]

        recommendations = []

        for profile in weak_profiles[:max_recommendations]:
            recommendation = self._create_recommendation(student, profile)
            if recommendation:
                recommendations.append(recommendation)

        return recommendations

    def _create_recommendation(self, student, profile):
        """创建单个推荐"""
        analysis_service = AnalysisService()

        # 计算边际收益
        marginal_gain = analysis_service.calculate_marginal_gain(
            student, profile.knowledge_point
        )

        if marginal_gain <= 0:
            return None

        # 确定推荐类型
        recommendation_type = self._determine_recommendation_type(profile, marginal_gain)

        # 估计学习时间（分钟）
        time_estimate = self._estimate_study_time(profile)

        # 创建推荐记录
        recommendation = StudyRecommendation.objects.create(
            student=student,
            knowledge_point=profile.knowledge_point,
            recommendation_type=recommendation_type,
            priority_score=self._calculate_priority_score(profile, marginal_gain),
            expected_improvement=marginal_gain,
            time_estimate=time_estimate,
            study_strategy=self._generate_study_strategy(profile, recommendation_type),
            expires_at=timezone.now() + timezone.timedelta(days=7)  # 推荐有效期7天
        )

        return recommendation

    def _determine_recommendation_type(self, profile, marginal_gain):
        """确定推荐类型"""
        if profile.mastery_level < 0.3:
            return 'weak_point'
        elif marginal_gain > 3:
            return 'high_yield'
        elif profile.mastery_trend == 'improving':
            return 'trending'
        else:
            return 'quick_win'

    def _estimate_study_time(self, profile):
        """估计学习时间"""
        if profile.mastery_level < 0.3:
            return 120  # 基础薄弱，需要较长时间
        elif profile.mastery_level < 0.6:
            return 60  # 中等水平，中等时间
        else:
            return 30  # 接近掌握，短时间复习

    def _calculate_priority_score(self, profile, marginal_gain):
        """计算优先级分数"""
        # 基于掌握度、边际收益、学习状态综合计算
        base_score = (1 - profile.mastery_level) * 0.6  # 掌握度权重60%
        gain_score = (marginal_gain / 5) * 0.3  # 边际收益权重30%
        status_score = 0.1 if profile.learning_status == 'struggling' else 0.0

        return min(1.0, base_score + gain_score + status_score)

    def _generate_study_strategy(self, profile, rec_type):
        """生成学习策略"""
        strategies = {
            'weak_point': f"系统学习{profile.knowledge_point.name}的基础概念，建议从教材第一章开始，配合基础练习题。",
            'high_yield': f"重点突破{profile.knowledge_point.name}，这是高分值知识点，掌握后能显著提升分数。",
            'quick_win': f"快速复习{profile.knowledge_point.name}，你已具备基础，稍加练习即可掌握。",
            'trending': f"继续保持{profile.knowledge_point.name}的学习势头，你正在快速提升这个知识点。"
        }

        return strategies.get(rec_type, f"建议学习{profile.knowledge_point.name}相关内容。")

    def get_active_recommendations(self, student):
        """获取活跃的推荐"""
        return StudyRecommendation.objects.filter(
            student=student,
            is_completed=False,
            expires_at__gt=timezone.now()
        ).order_by('-priority_score')